package com.sun.androidexerciseproject.function.android;

import android.content.Context;
import android.util.ArrayMap;
import android.view.accessibility.AccessibilityManager;

import com.sun.androidexerciseproject.function.util.LogUtil;

import java.util.Map;

/**
 * Description:
 * File: AndroidSystemServiceRegistry.java
 * Author: Administrator
 * Create: 2019/11/20 11:33
 */
public final class AndroidSystemServiceRegistry {
    private static final String TAG = AndroidSystemServiceRegistry.class.getSimpleName();

    private static final Map<Class<?>, String> SYSTEM_SERVICE_NAMES =
            new ArrayMap<>();
    private static final Map<String, AndroidServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
            new ArrayMap<>();

    static {
        registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class, new CachedServiceFetcher<AccessibilityManager>() {

            @Override
            public AccessibilityManager createService() {
                LogUtil.log("AccessibilityManager createService!!!");
                return null;
            }
        });
    }

    private AndroidSystemServiceRegistry() {

    }

    private static <T> void registerService(String serviceName, Class<T> serviceCls, AndroidServiceFetcher<T> serviceFetcher) {
        SYSTEM_SERVICE_NAMES.put(serviceCls, serviceName);
        SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
    }

    public static String getSystemServiceName(Class<?> serviceCls) {
        return SYSTEM_SERVICE_NAMES.get(serviceCls);
    }

    public static Object getSystemService(String name) {
        AndroidServiceFetcher serviceFetcher = SYSTEM_SERVICE_FETCHERS.get(name);
        return (null != serviceFetcher) ? serviceFetcher.getService() : null;

    }

    interface AndroidServiceFetcher<T> {
        T getService();
    }

    static abstract class CachedServiceFetcher<T> implements AndroidServiceFetcher<T> {
        @Override
        public T getService() {
            LogUtil.log("getService!!!");
            return createService();
        }

        public abstract T createService();
    }
}
